// Function for saving the user's settings
function saveCfg() {
    // Set the user's settings to the states of the checkboxes
    localStorage["copyLink"] = document.getElementById("copyLinkChk").checked;
    localStorage["showQr"] = document.getElementById("showQrChk").checked;
    localStorage["altIcon"] = document.getElementById("altIconChk").checked;

    // Change the browser action icon to the one the user chose
    if (toBool(localStorage["altIcon"]))
        chrome.browserAction.setIcon({path:"icons/alt_action.png"});
    else
        chrome.browserAction.setIcon({path:"icons/action.png"});

    // Display a message indicating settings were saved
    if (document.getElementById("message").style.opacity == "100")
    {
        document.getElementById("message").style.opacity = "0";
        setTimeout(showMessage, 500);
    }
    else
        showMessage();
}

// Function for showing the message that settings were saved
function showMessage() {
    document.getElementById("message").style.opacity = "100";
}

// Function for connecting a Google Account with OAuth
function connectAccount() {
    bgPage.oauth.authorize(function(a, b) {
        location.reload();
    });
}

// Function for disconnecting a Google Account with OAuth
function disconnectAccount() {
    bgPage.oauth.clearTokens();
    location.reload();
}

// Initialize the options page
document.addEventListener('DOMContentLoaded', function () {
    // Set event listeners for when various elements on the page are clicked
    document.getElementById('copyLinkChk').addEventListener('click', saveCfg);
    document.getElementById('showQrChk').addEventListener('click', saveCfg);
    document.getElementById('altIconChk').addEventListener('click', saveCfg);
    document.getElementById('connectLnk').addEventListener('click', connectAccount);
    document.getElementById('disconnectLnk').addEventListener('click', disconnectAccount);
    
    // Load the user's current configuration
    loadCfg();
    document.getElementById('copyLinkChk').checked = copyLink;
    document.getElementById('showQrChk').checked = showQr;
    document.getElementById('altIconChk').checked = altIcon;
    
    // Check to see if the user already connected a Google Account
    bgPage = chrome.extension.getBackgroundPage();
    if (bgPage.oauth.hasToken()) {
        document.getElementById('connectAccount').style.display = 'none';
        document.getElementById('connectedAccount').style.display = 'inline';
    }
});